import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86187
 * Date: 2022-10-17
 * Time: 10:11
 */
public class UdpEchoServe {
    // 面向数据报的.
    private DatagramSocket socket = null;

    public UdpEchoServe(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    // 启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动!");
        while(true) {
            // 循环处理请求

            // 1. 接收客户端发送的请求并解析
                // 面向数据报的.    byte[4096] 用于存储请求的内容
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket); // 接收请求
                // 将请求转为 字符串
            String request = new String(requestPacket.getData(),0, requestPacket.getLength());

            // 2. 处理请求
            String response = process(request);

            // 3. 将响应写回客户端(需要明确客户端的IP和端口号).
            DatagramPacket responseSocket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                                                                // getSocketAddress 包含了客户端的IP和端口号
                    requestPacket.getSocketAddress());
            socket.send(responseSocket);

            // 4. 打印一个日志
            System.out.printf("[%s : %d] request : %s; response : %s\n",requestPacket.getAddress().toString(),
                                            requestPacket.getPort(),request,response);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServe serve = new UdpEchoServe(9090);
        serve.start();
    }
}
